package oceanpayment

import (
    "fmt"
	"errors"
	//"wxsdk/utils/mapstruct"
	"github.com/astaxie/beego"
)

type RefundReq struct {
	Account           string `form:"account"`
	Terminal          string `form:"terminal"`
	SignValue         string `form:"signValue"`
	PaymentId         string `form:"payment_id"`
	RefundNumber      string `form:"refund_number,omitempty"`
	RefundType        string `form:"refund_type"`
	RefundAmount      string `form:"refund_amount"`
	RefundDescription string `form:"refund_description"`
}

type RefundRsp struct {
	Account           string `xml:"account"`
	Terminal          string `xml:"terminal"`
	SignValue         string `xml:"signValue"`
	PaymentId         string `xml:"payment_id"`
	RefundNumber      string `xml:"refund_number"`
	RefundId          string `xml:"refund_id"`
	RefundResults     string `xml:"refund_results"`
	RefundDescription string `xml:"refund_description"`
}

func Refunds(account,terminal,outerPayId,orderId,refundType,refundAmount,description,key string)(rsp *RefundRsp, err error){

	req := new(RefundReq)
	req.Account = account
	req.Terminal = terminal
	req.PaymentId = outerPayId
	req.RefundNumber = orderId
	req.RefundType = refundType
	req.RefundAmount = refundAmount
	req.RefundDescription = description
	req.SignValue = makeRefundSign(req, key)
	reqURL := "https://query.oceanpayment.com/service/applyRefund"
	sdk := NewSDK(reqURL)
	rsp = new(RefundRsp)
	_, err = sdk.Request(req, rsp)
	if err != nil {
		beego.Debug("Oceanpay Refunds err:", err.Error())
		return
	}
	if rsp.RefundResults != "00" {
	   err = errors.New(rsp.RefundResults)
	}
	return
}

func makeRefundSign(refundPay *RefundReq, key string) string {
	str := refundPay.Account
	str += refundPay.Terminal
	str += refundPay.PaymentId
	str += refundPay.RefundNumber
	str += refundPay.RefundType
	str += refundPay.RefundAmount
	str += refundPay.RefundDescription
	str += key
	return fmt.Sprintf("%x", sHA256([]byte(str)))
}
